<?php

namespace App\Http\Controllers\Wx;

use App\Http\Controllers\WxController;
use App\Models\Shop\Store;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class CartController extends WxController
{
    public function getIndex()
    {
        $cart = [];
        if(isset($_COOKIE['cart']))
        {
            $cartCookie = json_decode($_COOKIE['cart']);
            if(count($cartCookie) > 0)
            {
                $src = [];
                $cartOld = [];
                foreach($cartCookie as $c)
                {
                    $cartOld[$c[0]] = $c;
                    array_push($src, $c[0]);
                }
                $cart = DB::table('shop_store_goods')
                    ->join('shop_goods', 'shop_store_goods.goodsID', '=', 'shop_goods.id')
                    ->whereIn('shop_store_goods.id', $src)
                    ->select('shop_store_goods.id', 'shop_store_goods.storeID', 'shop_store_goods.amount', 'shop_store_goods.realAmount', 'shop_store_goods.number', 'shop_store_goods.display',
                        'shop_goods.classifyID', 'shop_goods.title', 'shop_goods.thumb', 'shop_goods.abstract')
                    ->orderBy('id', 'desc')
                    ->get();

                foreach($cart as $k=>$v)
                {
                    $cart[$k]->shopNum = $cartOld[$v->id][2];
                }
            }
        }
        return view('wx.cart')->with(['cart' => $cart]);
    }

    public function postPay(Request $request)
    {
        if(!$request->has('address') || $request->input('address') == '')
        {
            $backData = [
                'code'      =>  400,
                'msg'       =>  '请选择送货地址'
            ];

            return json_encode($backData);
        }
        if(!$request->has('shopTime') || $request->input('shopTime') == '')
        {
            $backData = [
                'code'      =>  400,
                'msg'       =>  '请选择配送时间'
            ];

            return json_encode($backData);
        }

        if(isset($_COOKIE['cart']))
        {
            $cartCookie = json_decode($_COOKIE['cart']);
            if(count($cartCookie) > 0)
            {
                $src = [];
                $cartOld = [];
                foreach($cartCookie as $c)
                {
                    $cartOld[$c[0]] = $c;
                    array_push($src, $c[0]);
                }
                $cart = DB::table('shop_store_goods')
                    ->join('shop_goods', 'shop_store_goods.goodsID', '=', 'shop_goods.id')
                    ->whereIn('shop_store_goods.id', $src)
                    ->select('shop_store_goods.id', 'shop_store_goods.storeID', 'shop_store_goods.amount', 'shop_store_goods.realAmount', 'shop_store_goods.number', 'shop_store_goods.display',
                        'shop_goods.classifyID', 'shop_goods.title', 'shop_goods.thumb', 'shop_goods.abstract')
                    ->orderBy('id', 'desc')
                    ->get();
                $storeID = 1;
                if(isset($_COOKIE['storeID']) && is_numeric($_COOKIE['storeID']))
                {
                    $storeID = $_COOKIE['storeID'];
                }
                $store = Store::find($storeID);

                $body = '千果屋商品-'.$store->name;
                $detail = '';
                $orderID = 'QGW'.$store->id.$this->getMillisecond().rand(1000,9999);
                $sum = 0;
                foreach($cart as $k=>$v)
                {
                    $cart[$k]->shopNum = $cartOld[$v->id][2];
                    if(count($cart) - $k == 1)
                    {
                        $detail .= $v->title.' x '.$cartOld[$v->id][2];
                    }else{
                        $detail .= $v->title.' x '.$cartOld[$v->id][2].',';
                    }
                    $sum += $cartOld[$v->id][2] * $v->realAmount;
                }
                /*
                 * 配送费
                 */
                if($sum < 10)
                {
                    $detail .= ',配送费 x 1';
                    $sum += 1;
                }
                /*
                 * 加入订单
                 */
                $orderData = [
                    'uid'               =>  $this->user->id,
                    'address'           =>  $request->input('address'),
                    'shopTime'          =>  $request->input('shopTime'),
                    'orderNumber'       =>  $orderID,
                    'storeID'           =>  $storeID,
                    'orderList'         =>  $detail,
                    'amount'            =>  $sum,
                    'payState'          =>  0,
                    'logisticsState'    =>  0,
                    'remark'            =>  ''
                ];
                $checkOrderID = \App\Models\Shop\Order::where('orderNumber', $orderID)->first();
                if($checkOrderID)
                {
                    $backData = [
                        'code'      =>  400,
                        'msg'       =>  '订单重复'
                    ];

                    return json_encode($backData);
                }
                $check = \App\Models\Shop\Order::create($orderData);
                if($check)
                {
                    /*
                 * 统一下单
                 */
                    $app = new Application(config('wechat'));
                    $payment = $app->payment;
                    $attributes = [
                        'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                        'body'             => $body,
                        'detail'           => $detail,
                        'out_trade_no'     => $orderID,
                        'total_fee'        => $sum * 100,
                        'notify_url'       => action('Api\WechatController@postNotify'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                        'openid'           => $this->user->openID, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                        // ...
                    ];
                    $order = new Order($attributes);

                    $result = $payment->prepare($order);

                    if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                        $prepayId = $result->prepay_id;
                        $config = $payment->configForJSSDKPayment($prepayId);
                        $config['timeStamp'] = $config['timestamp'];
                        unset($config['timestamp']);

                        $backData = [
                            'code'      =>  200,
                            'msg'       =>  'success',
                            'config'    =>  $config
                        ];
                        return json_encode($backData);
                    }else{
                        $backData = [
                            'code'      =>  400,
                            'msg'       =>  '异常错误'
                        ];

                        return json_encode($backData);
                    }
                }else{
                    $backData = [
                        'code'      =>  400,
                        'msg'       =>  '异常错误'
                    ];

                    return json_encode($backData);
                }
            }
        }
        $backData = [
            'code'      =>  400,
            'msg'       =>  '购物车为空,请刷新页面'
        ];

        return json_encode($backData);
    }

    public function getGetCart()
    {
        $cart = [];
        if(isset($_COOKIE['cart']))
        {
            $cartCookie = json_decode($_COOKIE['cart']);
            if(count($cartCookie) > 0)
            {
                $src = [];
                $cartOld = [];
                foreach($cartCookie as $c)
                {
                    $cartOld[$c[0]] = $c;
                    array_push($src, $c[0]);
                }
                $cart = DB::table('shop_store_goods')
                    ->join('shop_goods', 'shop_store_goods.goodsID', '=', 'shop_goods.id')
                    ->whereIn('shop_store_goods.id', $src)
                    ->select('shop_store_goods.id', 'shop_store_goods.storeID', 'shop_store_goods.amount', 'shop_store_goods.realAmount', 'shop_store_goods.number', 'shop_store_goods.display',
                        'shop_goods.classifyID', 'shop_goods.title', 'shop_goods.thumb', 'shop_goods.abstract')
                    ->orderBy('id', 'desc')
                    ->get();

                $html = '';
                $sum = 0;
                foreach($cart as $k=>$v)
                {
                    $html .= '<tr id="pay-'.$v->id.'">';
                    $html .= '<td>'.$v->title.'</td>';
                    $html .= '<td class="text-center">'.$v->realAmount.'</td>';
                    $html .= '<td class="text-center">'.$cartOld[$v->id][2].'</td>';
                    $html .= '<td class="text-center">'.$v->realAmount * $cartOld[$v->id][2].'</td>';
                    $html .= '</tr>';
                    $sum += $v->realAmount * $cartOld[$v->id][2];
                }
                if($sum < 10)
                {
                    $html .= '<tr>';
                    $html .= '<td>配送费(未满10円)</td>';
                    $html .= '<td class="text-center">1</td>';
                    $html .= '<td class="text-center">1</td>';
                    $html .= '<td class="text-center">1</td>';
                    $html .= '</tr>';
                }
                return json_encode([
                    'code'      =>  1,
                    'data'      =>  $html
                ]);
            }
        }
        return json_encode([
            'code'      =>  0,
            'msg'       =>  'error'
        ]);
    }

    private function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
}
